package com.xing.dao.impl;

import com.xing.dao.UserDao;
import com.xing.domain.User;
import com.xing.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Connection;
import java.sql.SQLException;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day38web2
 * 2021/4/28 15:13
 */
public class UserDaoImpl implements UserDao {

    //查询运行程序 QreryRunner类(org.apache.commons.dbutils.QueryRunner)
    // 是Dbutils的核心类之一，它显著的简化了SQL查询，
    // 并与ResultSetHandler协同工作将使编码量大为减少
    private QueryRunner qr=new QueryRunner();
    @Override
    public void insert(User user) {
        Connection connection = DataSourceUtils.getConnection();
        Object[] params={user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),user.getRole(),user.getCode()};
        try {
            qr.update(connection,"insert into tb_user(id,username,password,email,gender,flag,role,code) values (null ,?,?,?,?,?,?,?)",params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DataSourceUtils.closeAll(null, null, connection);
        }

    }

    @Override
    public User selectByUserAndPassword(String username, String password) {
        Connection connection = DataSourceUtils.getConnection();
        try {
           return  qr.query(connection,"select * from tb_user where username=? and password=?",new BeanHandler<>(User.class),username,password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DataSourceUtils.closeAll(null, null, connection);
        }
    }

    @Override
    public boolean selectByUserName(String username) {
        Connection connection = DataSourceUtils.getConnection();
        try {
            User user = qr.query(connection, "select * from tb_user where username=? ", new BeanHandler<>(User.class), username);
            if(user==null){
                return false;
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DataSourceUtils.closeAll(null, null, connection);
        }
    }
}
